import React, { FC, useRef, useEffect, useContext } from 'react'
import { Modal, Form, Input, Select, Upload, Button, message } from 'antd'
import { ModalProps } from 'antd/lib/modal'
import { rulesMessage, ERules } from '../../../constant'
import { FormInstance } from 'antd/lib/form';
import useRequest from '../../../hooks/useRequest';
import { Context } from '../index'

interface IProps extends ModalProps {
    handleOk?: () => void
    handleCancel?: () => void
}

const defaultFormProps = {
    labelAlign: 'right' as any,
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
}

interface Request {
    configClassify: (params: any) => Promise<any>
}
const NewModal: FC<IProps> = ({ visible, handleOk, handleCancel, confirmLoading }) => {
    const formRef = useRef<FormInstance | null>(null)
    const request = useRequest<Request>({ modulePath: 'picClassify' })
    const { state, dispatch } = useContext(Context)
    const { formData, id } = state
    const onOk = () => {
        formRef.current?.validateFields().then(async (values: any) => {
            const params = id === 0 ? ({ ...values }) : ({ ...values, id })
            const res = await request.configClassify(params)
            if (res) {
                message.success('操作成功')
            }
            handleOk && handleOk()
        }).catch(e => {
            console.log(e)
        })

    }
    const onCancel = () => {
        handleCancel && handleCancel()
    }
    const afterClose = () => {
        formRef.current?.resetFields()
    }
    useEffect(() => {
        formRef.current?.setFieldsValue(formData)

    }, [formData])
    return <Modal
        title={id === 0 ? '新增分类' : '修改分类'}
        visible={visible}
        onOk={onOk}
        confirmLoading={confirmLoading}
        onCancel={onCancel}
        afterClose={afterClose}
        destroyOnClose={true}
        getContainer={false}
    >
        <Form {...defaultFormProps} ref={formRef}>
            <Form.Item
                label="分类名称"
                name="classify_name"
                rules={[{ required: true, message: rulesMessage(ERules.REQUIRED, '分类名称') }]}
            >
                <Input placeholder="请输入分类名称" />
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(NewModal) 